#include "unp.h"

int main(){
	struct sockaddr_in	servaddr, cliaddr;
	socklen_t	len;
	int listenfd, connfd;

	if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		err_sys("socket error");

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(8888);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
		err_sys("bind error");

	if( listen(listenfd, 100) < 0)
		err_sys("listen error");
	
	char buf[MAXLINE + 1];
	char *p = buf;
	char c;
	int n ;
	while(1){
		if( (connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &len)) < 0)
			err_sys("accept error");

		while( (n = read(connfd, buf, sizeof(buf))) > 0){
			if(strncmp(buf, "quit", 4) == 0)
				break;
			write(connfd, buf, n);
		}
		if(n < 0)
			err_sys("read error");
		close(connfd);
	}
}
